package com.yuntongxun.ecdemo.rest;

import android.content.SharedPreferences;
import android.util.Log;

import com.yuntongxun.ecdemo.common.utils.ECPreferenceSettings;
import com.yuntongxun.ecdemo.common.utils.ECPreferences;

import java.util.HashMap;

import retrofit.RequestInterceptor;
import retrofit.client.Header;
import retrofit.client.Response;

/**
 * Created by EVE on 2016/4/17.
 */
public class CookieManager implements RequestInterceptor {

    private HashMap<String, String> _cookies = new HashMap<String, String>();
    private static CookieManager _instance = null;

    static {
        _instance = new CookieManager();
    }

    private CookieManager() {
        loadCookies();
    }

    public static CookieManager getInstance()
    {
        return _instance;
    }

    private void setCookies(String cookie) {
        String[] items = cookie.split(";");
        for (String item : items) {

            String[] kvs = item.split("=");
            if (kvs != null && kvs.length > 0) {
                if (kvs.length == 1) {
                    this._cookies.put(kvs[0].trim(), "");
                } else if (kvs.length == 2) {
                    _cookies.put(kvs[0].trim(), kvs[1].trim());
                } else {
                    Log.e("NET", "Invalid Set-Cookie");
                }
            }
        }
    }

    @Override
    public void intercept(RequestInterceptor.RequestFacade request) {
        if (_cookies != null) {
            String cookieStr = "";
            for (String key : _cookies.keySet()) {
                String val = _cookies.get(key);
                if (val != null && val.length() > 0) {
                    cookieStr += key + "=" + val + "; ";
                } else {
                    cookieStr += key + "; ";
                }
            }
            request.addHeader("Cookie", cookieStr);
        }
    }

    public void executeSetCookie(Response response) {
        for (Header header : response.getHeaders()) {
            if (null != header.getName() && header.getName().equals("Set-Cookie")) {
                String setCookies = header.getValue();
                if (setCookies != null) {
                    Log.d("Set-Cookie", setCookies);
                    setCookies(setCookies);
                }
            }
        }
        saveCookies();
    }

    private void saveCookies() {
        String cks = "";
        for(String key : _cookies.keySet()) {
            cks += key + "=" + _cookies.get(key) + ";";
        }
        SharedPreferences sharedPreferences = ECPreferences.getSharedPreferences();
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("cookies_archive", cks);
        editor.commit();
    }

    private void loadCookies() {
        SharedPreferences sharedPreferences = ECPreferences.getSharedPreferences();
        String cks = sharedPreferences.getString("cookies_archive", null);
        if(cks == null || cks.isEmpty())
            return;
        String[] pairs = cks.split(";");
        for(String pair : pairs) {
            String[] kvp = pair.split("=");
            if(kvp != null && kvp.length > 1) {
                if(!_cookies.containsKey(kvp[0])) {
                    _cookies.put(kvp[0], kvp[1]);
                }
            }
        }
    }
}
